package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.dao.OrderDao;
import com.atguigu.pojo.Address;
import com.atguigu.pojo.Member;
import com.atguigu.service.*;
import com.atguigu.utils.DateUtils;
import com.atguigu.vo.Result;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

/**
 * @program: meinian_parent
 * @author: Mr.Zhuo
 * @create: 2022-02-19 21:43
 **/
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;


    @Reference
    ReportService reportService;

    @Reference
    AddressService addressService;


    @GetMapping("/findAllMaps")
    public Map<String, List<Map<String, Object>>> findAllMaps() {
        Map mapVO=new HashMap();
        // 从数据库中查询所有的数据
        List<Address> addressList = addressService.findAll();
        List<Map<String, Object>> gridnMaps = new ArrayList<>();
        List<Map<String, Object>> nameMaps = new ArrayList<>();

        // 然后循环遍历放在指定的数据类型当中
        for (Address address : addressList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("lng", address.getLng());
            map.put("lat", address.getLat());
            gridnMaps.add(map);

            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("addressName", address.getAddressName());
            nameMaps.add(map1);
        }
        // 存放经纬度
        mapVO.put("gridnMaps",gridnMaps);
        // 存放名字
        mapVO.put("nameMaps",nameMaps);

        return mapVO;
    }


    /**
     * 统计分析套餐占比
     *
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            // 需要数据绑定的是两种形式的数据
            // 首先调用service层直接把所有需要的数据都调取出来
            List<Map<String, Object>> mapDB = setmealService.findSetmealNamesAndSetmealCount();

            // ["":"","":""] list集合的元素为Map
            Map<String, Object> map = new HashMap<>();
            map.put("setmealCount", mapDB);

            // ["","",""] list集合的元素为String
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> objectMap : mapDB) {
                String names = (String) objectMap.get("name");
                setmealNames.add(names);
            }

            // 首先返回的事一个map集合
            map.put("setmealNames", setmealNames);
            map.put("setmealCount", mapDB);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 获取统计分析会员数量
     *
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        try {
            // 获取日历对象
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -12);
            ArrayList<String> months = new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);
                months.add(format.format(calendar.getTime()));
            }

            // 根据日期来查询数量
            ArrayList<Integer> memberCount = memberService.findMemberCountByMonth(months);

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("months", months);
            hashMap.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, hashMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        try {
            Map<String, Object> businessReport = reportService.getBusinessReport();

            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, businessReport);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 统计分析运营数据 到处excel
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 首先获取报表数据
            Map<String, Object> businessReport = reportService.getBusinessReport();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) businessReport.get("reportDate");
            Integer todayNewMember = (Integer) businessReport.get("todayNewMember");
            Integer totalMember = (Integer) businessReport.get("totalMember");
            Integer thisWeekNewMember = (Integer) businessReport.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) businessReport.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) businessReport.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) businessReport.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) businessReport.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) businessReport.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) businessReport.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) businessReport.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) businessReport.get("hotSetmeal");

            // 然后我们获取excel的文件路径
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";

            // 读取excel表的对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));

            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日出游数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周出游数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月出游数

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            // 然后通过文件流进行传输下载
            ServletOutputStream outputStream = response.getOutputStream();
            // 下载类型
            response.setContentType("application/vnd.ms-excel");
            // 设置下载形式（以附件的形式下载）
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            workbook.write(outputStream);

            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
        }

    }


}
